﻿using Microsoft.Extensions.Logging;

namespace ThingsGateway.Application.Core
{
    public abstract class UpLoadBase : IDisposable
    {
        protected ILogger _logger;
        protected RootServices _rootServices;

        protected UploadDevice _uploadDevice;
        /// <summary>
        /// 约定构造实现
        /// </summary>
        public UpLoadBase(ILogger logger, RootServices rootServices)
        {
            _logger = logger;
            _rootServices = rootServices;
        }

        protected virtual void DeviceVariableCollectChange(DeviceVariable variable)
        {
            if (!_uploadDevice.InvokeEnable) return;

        }
        protected virtual void DeviceVariableValueChange(DeviceVariable variable)
        {
            if (!_uploadDevice.InvokeEnable) return;

        }
        protected virtual void AlarmChnage(DeviceVariable alarm)
        {
            if (!_uploadDevice.InvokeEnable) return;

        }

        protected virtual void DeviceStatusChnage(Device device)
        {
            if (!_uploadDevice.InvokeEnable) return;
        }

        protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
        private int isStoped;
        /// <summary>
        /// 开始通讯前执行的方法
        /// </summary>
        /// <returns></returns>
        public virtual async Task StartAsync(UploadDevice uploadDevice, CancellationToken stoppingToken)
        {
            _uploadDevice = uploadDevice;
            _rootServices.AlarmHostService.OnAlarmChanged += AlarmChnage;
            _rootServices.AlarmHostService.OnDeviceStatusChanged += DeviceStatusChnage;
            _rootServices.AllDeviceData.DeviceVariables?.ForEach(v => { v.VariableValueChange += DeviceVariableValueChange; });
            _rootServices.AllDeviceData.DeviceVariables?.ForEach(v => { v.VariableCollectChange += DeviceVariableCollectChange; });
            try
            {
                await ExecuteAsync(stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ToString());
            }
            Interlocked.CompareExchange(ref isStoped, 1, 0);

        }

        /// <summary>
        /// 开始通讯前执行的方法
        /// </summary>
        /// <returns></returns>
        public virtual async Task StopAsync()
        {
            _rootServices.AlarmHostService.OnAlarmChanged -= AlarmChnage;
            _rootServices.AlarmHostService.OnDeviceStatusChanged -= DeviceStatusChnage;
            await Task.Delay(1000);
            while (isStoped<=0)
            {
                await Task.Delay(1000);
            }
        }

        public abstract void Dispose();
    }
}
